package com.example.dw.controller;

import com.example.dw.common.Result;
import com.example.dw.dto.*;
import com.example.dw.entity.*;
import com.example.dw.service.ActivityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 活动控制器
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/active")
@Tag(name = "活动管理", description = "活动相关的API接口")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    /**
     * 根据ID获取活动详情
     */
    @GetMapping("/{activityid}")
    @Operation(summary = "根据ID获取活动详情", description = "根据活动ID获取活动详情")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "活动详情获取成功"),
            @ApiResponse(responseCode = "404", description = "活动不存在")
    })
    public Result<Activity> getActiveById(@PathVariable Integer activityid) {
        try {
            Activity activity = activityService.getActiveById(activityid);
            return Result.success(activity);
        } catch (Exception e) {
            log.error("根据ID获取活动详情失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页获取活动评论
     */
    @PostMapping("/commentPage")
    @Operation(summary = "分页获取活动评论", description = "根据活动ID分页获取活动评论")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "活动评论获取成功"),
            @ApiResponse(responseCode = "500", description = "获取活动评论失败")
    })
    public Result<Map<String, Object>> getActiveCommentByPage(HttpServletRequest request,
                                                               @Validated @RequestBody ActivityCommentDTO commentDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Map<String, Object> result = activityService.getActiveCommentByPage(commentDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页获取活动评论失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取活动评论Web版
     */
    @GetMapping("/commentPageE/{activityid}")
    @Operation(summary = "获取活动评论Web版", description = "根据活动ID获取活动评论列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "活动评论获取成功"),
            @ApiResponse(responseCode = "500", description = "获取活动评论失败")
    })
    public Result<List<ActivityComment>> getActiveComment(@PathVariable Integer activityid) {
        try {
            List<ActivityComment> comments = activityService.getActiveComment(activityid);
            return Result.success(comments);
        } catch (Exception e) {
            log.error("获取活动评论失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户添加评论
     */
    @PostMapping("/addComment")
    @Operation(summary = "用户添加评论", description = "用户根据活动ID添加评论")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "评论添加成功"),
            @ApiResponse(responseCode = "500", description = "添加评论失败")
    })
    public Result<Void> addActiveComment(HttpServletRequest request,
                                         @Validated @RequestBody ActivityCommentDTO commentDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            activityService.addActiveComment(userid, commentDTO);
            return Result.success("评论成功");
        } catch (Exception e) {
            log.error("添加活动评论失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户收藏/取消收藏活动
     */
    @PostMapping("/changeFavorite")
    @Operation(summary = "用户收藏/取消收藏活动", description = "用户根据活动ID切换收藏状态")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "收藏状态切换成功"),
            @ApiResponse(responseCode = "500", description = "切换收藏状态失败")
    })
    public Result<Void> changeFavorite(HttpServletRequest request,
                                       @Validated @RequestBody FavoriteDTO favoriteDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            favoriteDTO.setUserid(userid);
            activityService.changeFavorite(userid, favoriteDTO);
            return Result.success("操作成功");
        } catch (Exception e) {
            log.error("切换收藏状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查用户是否收藏了活动
     */
    @PostMapping("/isFavorite")
    @Operation(summary = "检查用户是否收藏了活动", description = "检查用户是否收藏了指定活动")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "检查成功"),
            @ApiResponse(responseCode = "500", description = "检查失败")
    })
    public Result<Boolean> isFavorite(HttpServletRequest request,
                                      @RequestBody FavoriteDTO favoriteDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Boolean isFavorite = activityService.isFavorite(userid, favoriteDTO.getActivityid());
            return Result.success(isFavorite);
        } catch (Exception e) {
            log.error("检查收藏状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页获取未过期活动信息
     */
    @PostMapping("/getActiveByPageIng")
    @Operation(summary = "分页获取未过期活动信息", description = "根据查询条件分页获取未过期活动信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "未过期活动获取成功"),
            @ApiResponse(responseCode = "500", description = "获取未过期活动失败")
    })
    public Result<Map<String, Object>> getActiveByPageIng(@RequestBody ActivityQueryDTO queryDTO) {
        try {
            Map<String, Object> result = activityService.getActiveByPageIng(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页获取未过期活动失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页获取过期活动信息
     */
    @PostMapping("/getActiveByPageEd")
    @Operation(summary = "分页获取过期活动信息", description = "根据查询条件分页获取过期活动信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "过期活动获取成功"),
            @ApiResponse(responseCode = "500", description = "获取过期活动失败")
    })
    public Result<Map<String, Object>> getActiveByPageEd(@RequestBody ActivityQueryDTO queryDTO) {
        try {
            Map<String, Object> result = activityService.getActiveByPageEd(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页获取过期活动失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取活动大类信息（分页）
     */
    @PostMapping("/getAllBigTypeByPage")
    @Operation(summary = "获取活动大类信息（分页）", description = "根据查询条件分页获取活动大类信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "活动大类信息获取成功"),
            @ApiResponse(responseCode = "500", description = "获取活动大类信息失败")
    })
    public Result<Map<String, Object>> getAllBigTypeByPage(@RequestBody ActivityQueryDTO queryDTO) {
        try {
            Map<String, Object> result = activityService.getAllBigTypeByPage(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取活动大类信息失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 按月份获取活动数据
     */
    @PostMapping("/activeByMonth")
    @Operation(summary = "按月份获取活动数据", description = "根据查询条件按月份获取活动数据")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "按月份活动数据获取成功"),
            @ApiResponse(responseCode = "500", description = "按月份获取活动数据失败")
    })
    public Result<Map<String, Object>> getActiveByMonth(@RequestBody ActivityQueryDTO queryDTO) {
        try {
            Map<String, Object> result = activityService.getActiveByMonth(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("按月份获取活动数据失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取客服二维码
     */
    @GetMapping("/getQR")
    @Operation(summary = "获取客服二维码", description = "获取所有客服二维码")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "客服二维码获取成功"),
            @ApiResponse(responseCode = "500", description = "获取客服二维码失败")
    })
    public Result<List<QR>> getQR() {
        try {
            List<QR> qrList = activityService.getQR();
            return Result.success(qrList);
        } catch (Exception e) {
            log.error("获取客服二维码失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取该月份内全部活动
     */
    @PostMapping("/activeByMonthAll")
    @Operation(summary = "获取该月份内全部活动", description = "根据月份获取该月份内全部活动")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "月份内全部活动获取成功"),
            @ApiResponse(responseCode = "500", description = "获取月份内全部活动失败")
    })
    public Result<List<Activity>> getActiveByMonthAll(@RequestBody ActivityQueryDTO queryDTO) {
        try {
            List<Activity> activities = activityService.getActiveByMonthAll(queryDTO.getMonth());
            return Result.success(activities);
        } catch (Exception e) {
            log.error("获取月份内全部活动失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据活动大类分页获取活动信息
     */
    @PostMapping("/getActivedByPage")
    @Operation(summary = "根据活动大类分页获取活动信息", description = "根据活动大类分页获取活动信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "活动信息获取成功"),
            @ApiResponse(responseCode = "500", description = "获取活动信息失败")
    })
    public Result<Map<String, Object>> getActivedByPage(@RequestBody ActivityQueryDTO queryDTO) {
        try {
            Map<String, Object> result = activityService.getActivedByPage(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("根据活动大类分页获取活动失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 从请求中获取当前用户ID
     */
    private Integer getCurrentUserId(HttpServletRequest request) {
        Integer userid = (Integer) request.getAttribute("userid");
        if (userid == null) {
            throw new RuntimeException("未授权访问");
        }
        return userid;
    }
} 